/* ====================================================
#   Copyright (C)2019 Li Jianbin All rights reserved.
#
#   Author        : Li Jianbin
#   Email         : lijianbinmail@163.com
#   File Name     : cmakewindow.cpp
#   Last Modified : 2019-04-21 11:00
#   Describe      : Main Window
#
# ====================================================*/

#include "cmainwindow.h"
#include "ui_cmainwindow.h"



CMainWindow::CMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CMainWindow)
{
    ui->setupUi(this);
    setMouseTracking(true);
    initUIs();
    // initModels();
    initSignals();

}

CMainWindow::~CMainWindow()
{
    delete ui;
}

void CMainWindow::initUIs()
{
    splitter = new QSplitter(Qt::Horizontal);
    splitter->setOpaqueResize(false);
    this->setCentralWidget(splitter);
    stack = new QStackedWidget(splitter);
    stack->setMidLineWidth(100);
    scControl = new ScenceControl;
    modc = new ModelControl;
    stack->addWidget(scControl);
    stack->addWidget(modc);
    m_3d_widget = new C3DWidget(splitter);
    splitter->setStretchFactor(1,1);
    // ui->statusBar->setVisible(false);

    msgLabel = new QLabel;
    msgLabel->setStyleSheet(" QLabel{ color: red }");
    ui->statusBar->addWidget(msgLabel);

    mouseGroup = new QActionGroup(ui->menuBar);
    mouseGroup->addAction(ui->actionNormal);
    mouseGroup->addAction(ui->actionScale);
    mouseGroup->addAction(ui->actionMove);

}

void CMainWindow::initSignals()
{
    //! 显示一串轨迹--showPolygonPath---showAxles--genAnimations
    connect(scControl,&ScenceControl::CommitPaths,m_3d_widget,&C3DWidget::showAxles);

    //! 修改相机的位置
    connect(scControl,&ScenceControl::CommitCamMove,m_3d_widget,&C3DWidget::setCameraPosition);

    //!* 设置场景渲染
    connect(scControl,&ScenceControl::CommitConfig,m_3d_widget,&C3DWidget::setRelateParament);

    //! 改变选中对象位置
    connect(modc,&ModelControl::changePosition,this,[=](sys::ControlObject index,Pos3dzx pos){
        qDebug()<< index << pos.x;
        switch (index) {
        case sys::ENUM_ROBOT:
            for ( m_3d_widget->m_get_context()->InitSelected();
                  m_3d_widget->m_get_context()->MoreSelected();
                  m_3d_widget->m_get_context()->NextSelected() ){
                try {
                    OCC_CATCH_SIGNALS
                    m_3d_widget->setLocation(m_3d_widget->m_get_context()->SelectedInteractive(),pos,true);
                } catch (Standard_Failure e) {
                    qDebug()<<"------------->"<<e.GetMessageString();
                }
            }
        break;
        case sys::ENUM_MACHINE:
        break;
        case sys::ENUM_TCP:
        break;
        }

    }, Qt::AutoConnection);

    //!* 显示实时位置
    connect(m_3d_widget,&C3DWidget::showPosition,this,[=](Pos3dzx pos){
        msgLabel->setText("("+QString::number(round(pos.x))+","+QString::number(round(pos.y))+","+QString::number(round(pos.z))+")");
    });


    //! 模型相对运动
    connect(modc,&ModelControl::relativePositon,this,[=](sys::ControlObject index,Pos3dzx pos){
        qDebug()<< index << pos.x;
        switch (index) {
        case sys::ENUM_ROBOT:
            for ( m_3d_widget->m_get_context()->InitSelected();
                  m_3d_widget->m_get_context()->MoreSelected();
                  m_3d_widget->m_get_context()->NextSelected() ){
                try {
                    OCC_CATCH_SIGNALS
                    m_3d_widget->relativeMove(m_3d_widget->m_get_context()->SelectedInteractive(),pos);
                } catch (Standard_Failure e) {
                    qDebug()<<"------------->"<<e.GetMessageString();
                }
            }
        break;
        case sys::ENUM_MACHINE:
        break;
        case sys::ENUM_TCP:
        break;
        }
    });

}

void CMainWindow::initModels()
{
    machine_model = new CModel(true,"/home/td/models/wind.STEP");
    disPlayModel(machine_model);
}

void CMainWindow::on_actionMkCube_triggered()
{
    m_3d_widget->make_cube();
}

void CMainWindow::on_actionMkCylinder_triggered()
{
    m_3d_widget->make_cylinder();
}

void CMainWindow::on_actionMkSphere_triggered()
{
    m_3d_widget->make_sphere();
}

void CMainWindow::on_actionMkCone_triggered()
{
    m_3d_widget->make_cone();
}

void CMainWindow::on_actionMkTorus_triggered()
{
    m_3d_widget->make_torus();
}

void CMainWindow::on_actionExport_triggered()
{// 触发导出模型文档
    // 判断模型是否被选择
    if(m_3d_widget->m_get_context()->NbSelected() == 0)
    {
        // 无选择则弹出提示框
        QMessageBox::warning(this,tr("Export Error"),tr("There is no object selected!"));
        return; // 不执行操作
    }

    QString t_all_filter; // 所有文件过滤器
    QHash<QString,const char *> t_hash_format;  // 格式过滤器与文档描述哈希表
    Exporter t_export;  // 导出器
    for(int i=0; i<t_export.GetExportFormatCount(); i++)    // 遍历ASSIMP允许导出的格式
    {
        const aiExportFormatDesc *t_format_desc = t_export.GetExportFormatDescription(i);   // 获取每个文档描述
        // 文档过滤器
        QString t_single_format = QString(t_format_desc->description)+QString("(*.%1)").arg(t_format_desc->fileExtension);
        t_hash_format.insert(t_single_format,t_format_desc->id);    // 插入格式过滤器与文档描述哈希表
        t_all_filter += t_single_format;    // 添加单个文档过滤到整体过滤器
        if(i != t_export.GetExportFormatCount()-1)  // 最后一个不添加分行
        {
            t_all_filter+=";;"; // 分行
        }
    }
    QString t_selected_filter; // 被选择的过滤器
    // 打开文件保存提示框
    QString filename = QFileDialog::getSaveFileName(this,tr("Save"),".",t_all_filter,&t_selected_filter);
    if(filename.isEmpty())  // 若文件名为空，则不执行操作
    {
        return; // 不执行操作
    }
    // 导出模型文件
    CModel::m_export_model(filename,t_hash_format.value(t_selected_filter),m_3d_widget->m_get_context());
}

void CMainWindow::on_actionReflush_triggered()
{
    // Erase(m_3d_widget->m_get_context());  // 擦除一个模型对象
    m_3d_widget->m_get_view()->FitAll();     // 自动填充当前视图
}

void CMainWindow::keyPressEvent(QKeyEvent *e)
{
    switch (e->key()) {
    case Qt::Key_Delete:
        printf("Key_Delete\n");
        // m_3d_widget->removeCurModel();
    break;
    case Qt::Key_Escape:
        printf("Key_Escape\n");
    break;
    case Qt::Key_F4:
        printf("Key_F4\n");
    break;
    case Qt::Key_Left:
        printf("Key_Left\n");
    break;
    case Qt::Key_Space:
    break;
    }
}

void CMainWindow::disPlayModel(CModel *t_model)
{
    t_model->SetColor(Quantity_NOC_MATRAGRAY);  // 为模型设置颜色　　避免屎黄色
    m_3d_widget->m_get_context()->Display(t_model,true);  // 显示模型

    // 选择整个导入的模型
    for(PrsMgr_ListOfPresentableObjectsIter i(t_model->Children());i.More();i.Next())
    {
        // 获取当前模型
        Handle(PrsMgr_PresentableObject) t_object = i.Value();
        // 若为CModel类型则转换为CModel
        if(t_object->IsKind(STANDARD_TYPE(CModel))) {
            Handle_CModel t_child_model =  Handle(CModel)::DownCast(t_object);
            // t_child_model->SetHilightMode(1);   // 设置高亮模式
            // 选择该模型（注：不选择过模型就AddSelect可能会出错）
            m_3d_widget->m_get_context()->SetSelected(t_child_model,true);
        }
    }
    // 选择该模型
    m_3d_widget->m_get_context()->SetSelected(t_model,true);
    // 三维界面显示该模型的全部
    m_3d_widget->m_get_view()->FitAll(t_model->m_get_full_aabb());
    m_3d_widget->bindCoordinate(t_model);   // 绑定盒子
    m_3d_widget->attachToPulator(t_model);
}



//bool checked
void CMainWindow::on_actionhideSelect_triggered()
{
    auto checked = ui->actionhideSelect->isChecked();
    if(!checked){
        m_3d_widget->m_get_context()->DisplayAll(true);
    }else{
        m_3d_widget->m_get_context()->EraseAll(true);
    }
    ui->actionhideSelect->setChecked(!checked);
}

void CMainWindow::on_actionstep_triggered()
{
    QString all_filter = "ASSIMP (*.step *.STEP);ALL (*.*)";
    // 获取被打开的文件路径
    QString filename = QFileDialog::getOpenFileName(this,tr("open file"),"/home/td/models/",all_filter);
    if(filename.isEmpty()) { // 若文件名为空，则不执行操作
        return;
    }
    CModel *t_model = new CModel(true,filename); // 创建模型
    disPlayModel(t_model);
}

void CMainWindow::on_actionassimp_format_triggered()
{
    // 获取ASSIMP支持的导入格式
    Importer t_importer;
    std::string szOut;
    t_importer.GetExtensionList(szOut); // ASSIMP支持的导入格式
    std::cout<<szOut<<std::endl;
    // 筛选文件格式
    QString t_assimp=tr("ASSIMP (") +QString::fromStdString(szOut) + tr("); ALL (*.*)");
    QString all_filter;
    all_filter+=t_assimp;
    all_filter = all_filter.replace(QRegExp("\\;"), " ");

    // 获取被打开的文件路径
    QString filename = QFileDialog::getOpenFileName(this,tr("open file"),"/home/td/models/",all_filter);
    if(filename.isEmpty()) { // 若文件名为空，则不执行操作
        return;
    }

    CModel *t_model = new CModel(filename); // 创建模型
    disPlayModel(t_model);
}

void CMainWindow::on_actionResize_triggered()
{
    m_3d_widget->m_get_view()->FitAll();     // 自动填充当前视图
}

void CMainWindow::on_actionMc_triggered()
{
    stack->setCurrentIndex(1);
}

void CMainWindow::on_action_Path_triggered()
{
    stack->setCurrentIndex(0);
}

void CMainWindow::on_actionNormal_triggered()
{
    m_3d_widget->setDefaultMouse(0);
}

void CMainWindow::on_actionMove_triggered()
{
    m_3d_widget->setDefaultMouse(2);
}

void CMainWindow::on_actionScale_triggered()
{
    m_3d_widget->setDefaultMouse(1);
}
